﻿using LaunchAllaround.DesignPattern.MVC;
using Microsoft.Kinect;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LaunchAllaround.Engine
{
    /// <summary>
    /// Logique d'interaction pour KinectView.xaml
    /// </summary>
    public partial class KinectView : UserControl, Controller<Kinect>, View<Kinect>
    {

        private Model<Kinect> model;

        public KinectView(Model<Kinect> model)
        {
            this.model = model;
            
            InitializeComponent();
        }

        public void Refresh(RefreshEvent<Kinect> ev)
        {
            if (ev is RefreshKinectStatus)
            {
                if (((RefreshKinectStatus)(ev)).Status == KinectStatus.Connected)
                {
                    this.KinectImage.Visibility = Visibility.Visible;
                }
                else
                {
                    this.KinectImage.Visibility = Visibility.Hidden;
                }
            }

            if (ev is RefreshFrames)
            {
                AllFramesReadyEventArgs args = ((RefreshFrames)ev).Args;

                // displaying the color stream from the kinect
                using (ColorImageFrame colorFrame = args.OpenColorImageFrame())
                {
                    if (colorFrame != null)
                    {
                        //Using standard SDK
                        byte[] colorPixelData;
                        WriteableBitmap outputImage;


                        colorPixelData = new byte[colorFrame.PixelDataLength];
                        colorFrame.CopyPixelDataTo(colorPixelData);

                        outputImage = new WriteableBitmap(
                        colorFrame.Width,
                        colorFrame.Height,
                        96,  // DpiX
                        96,  // DpiY
                        PixelFormats.Bgr32,
                        null);

                        outputImage.WritePixels(
                        new Int32Rect(0, 0, colorFrame.Width, colorFrame.Height),
                        colorPixelData,
                        colorFrame.Width * 4,
                        0);
                        this.img.Source = outputImage;
                    }
                }
            }
        }


        public Model<Kinect> GetModel()
        {
            return this.model;
        }

        public void SetModel(Model<Kinect> model)
        {
            this.model = model;
        }
    }
}
